package hy.controller;

import hy.beans.User;
import hy.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class UserController {
    @Autowired
    UserService service;
    @PostMapping("/regist")
    public String regist(User u, Model m){
        try {
            service.regist(u);
        }catch (Exception e){
            e.printStackTrace();
            m.addAttribute("err","注册失败");
            return "regist";
        }
        return "redirect:/showLogin";
    }

    @PostMapping("/login")
    public String login(User u, HttpSession session){
        UsernamePasswordToken tok = new UsernamePasswordToken(u.getUsername(),u.getPassword());
        //默认是从cookie中读取sessionId以此来维持会话。如果在分布式集群环境中可以把session放在redis管理，可以实现session共享，可自定义sessionManager，重写getSessionId方法。
        Subject sub = SecurityUtils.getSubject();
        String err=null;
        try{
            ////调用realm中的doGetAuthen,如果是sub.hasRole("manager")则会调用realm中的doGetAuthor
            sub.login(tok);
        }catch (AuthenticationException e) {
            err = "用户名或密码错误";
        }

        if(err==null){
            return "redirect:/showSuccess";
        }else{
            session.setAttribute("err",err);
        }
        return "redirect:/showLogin";
    }

    @RequestMapping("/logout")
    public String logout(){
        Subject sub = SecurityUtils.getSubject();
        sub.logout();
        return "redirect:/showLogin";
    }

    //@RequiresRoles({"admin"})
    @RequiresPermissions("product")
    @RequiresUser//任意认证用户都可以通过
    @RequestMapping("/test")
    @ResponseBody
    public String test(){
        return "你有权执行该操作";
    }
    @RequiresRoles({"admin"})
    @ResponseBody
    public String test21111(){
        return "你有权执行该操作";
    }
}